<template>
	<view>
		<view>
			<button @click="startRecording">开始录音</button>
			<button @click="stopRecording">停止录音</button>
		</view>
		<view>
			<text>接收到的消息：</text>
			<view>
				{{ message }}
			</view>
		</view>
	</view>
</template>

<script>
const recorderManager = uni.getRecorderManager();

import CryptoJS from 'crypto-js';
import md5 from 'md5';
// 在 Vue 组件中
export default {
	data() {
		return {
			WebSocket: null,
			resultText: '',
			message: '',
		};
	},
	methods: {
		getWebSocketUrl() {
			const url = "wss://rtasr.xfyun.cn/v1/ws";
			const appId = '89101ef5';
			const secretKey = '859ebc6d9264750f07d529b53dbf5dbe';
			const ts = Math.floor(new Date().getTime() / 1000);

			// 使用 md5 生成签名
			const signa = md5(appId + ts);

			// 使用 HmacSHA1 生成最终签名
			const signatureSha = CryptoJS.HmacSHA1(signa, secretKey);
			let signature = CryptoJS.enc.Base64.stringify(signatureSha);
			signature = encodeURIComponent(signature);

			return `${url}?appid=${appId}&ts=${ts}&signa=${signature}`;
		},
		// 初始化 WebSocket 连接
		initWebSocket() {
			this.WebSocket = uni.connectSocket({
				url: this.getWebSocketUrl(),
				success: (res) => {
					console.log('WebSocket连接成功', res);
				},

			});
			console.log('连接成功');
			this.WebSocket.onOpen(() => {
				recorderManager.start({
					sampleRate: 16000,
					frameSize: 1280,

				});
				console.log('WebSocket连接已经打开');
			});
			this.WebSocket.onMessage((res) => {
				console.log('接收到的消息:', res.data);
				this.renderResult(res.data);
			});

			// 错误事件
			this.WebSocket.onError((err) => {
				console.log('WebSocket错误:', err);
			});
			// 连接关闭事件
			this.WebSocket.onClose(() => {
				console.log('WebSocket连接关闭');
			});
		},
		playAudio(filePath) {
			const audioContext = uni.createInnerAudioContext();
			audioContext.src = filePath; // 设置音频文件路径

			audioContext.play(); // 播放音频
			audioContext.onPlay(() => {
				console.log('播放录音');
			});

			audioContext.onError((err) => {
				console.error('播放错误:', err);
			});
		},
		startRecording() {


			this.initWebSocket();  // 建立 WebSocket 连接
			recorderManager.onStop((res) => {
				console.log('录音停止:', res);
				const { tempFilePath } = res; // 获取录音文件的临时路径

				if (tempFilePath) {
					uni.showToast({
						title: '录音完成',
						icon: 'success'
					});
					console.log(tempFilePath, 'tempFilePath');

					// 使用录音文件（例如播放或上传）
					this.playAudio(tempFilePath);
					// uploadAudio(tempFilePath); // 如需上传可调用上传函数
				} else {
					uni.showToast({
						title: '录音失败，请重试',
						icon: 'none'
					});
				}
			});
			recorderManager.onFrameRecorded((res) => {
				const { frameBuffer } = res;
				console.log('frameBuffer.byteLength', frameBuffer.byteLength);
				// 通过分析frameBuffer的数据来计算音量
			});
			return

			// console.log(recorderManager,'recorderManager');
			// return
			recorderManager.onFrameRecorded = ({ isLastFrame, frameBuffer }) => {
				console.log(frameBuffer, 'frameBuffer');
				return
				if (this.WebSocket.readyState === this.WebSocket.OPEN) {
					this.WebSocket.send(new Int8Array(frameBuffer));
					if (isLastFrame) {
						this.WebSocket.send('{"end": true}');
						changeBtnStatus("CLOSING");
					}
				}
			};




		},
		stopRecording() {
			recorderManager.stop();  // 停止录音
			if (this.WebSocket) this.WebSocket.close();  // 关闭 WebSocket 连接
			console.log('录音已停止');
		},
		renderResult(resultData) {
			let jsonData = JSON.parse(resultData);
			if (jsonData.action == "started") {
				// 握手成功
				console.log("握手成功");
			} else if (jsonData.action == "result") {
				const data = JSON.parse(jsonData.data)
				console.log(data)
				// 转写结果
				let resultTextTemp = ""
				data.cn.st.rt.forEach((j) => {
					j.ws.forEach((k) => {
						k.cw.forEach((l) => {
							resultTextTemp += l.w;
						});
					});
				});
				if (data.cn.st.type == 0) {
					// 【最终】识别结果：
					this.resultText += resultTextTemp;
					resultTextTemp = ""
				}

				this.message = this.resultText + resultTextTemp
			} else if (jsonData.action == "error") {
				// 连接发生错误
				console.log("出错了:", jsonData);
			}
		},
		// 关闭 WebSocket 连接
		closeWebSocket() {
			if (this.WebSocket) {
				this.WebSocket.close({
					success: () => {
						console.log('WebSocket连接关闭成功');
					},
					fail: (err) => {
						console.log('WebSocket连接关闭失败', err);
					},
				});
			}
		},
	},
	// 页面加载时初始化 WebSocket
	onLoad() {
		let _this = this
		uni.authorize({
			scope: 'scope.record',
			success() {
				console.log('录音权限已授权');
				// 开始录音逻辑
				// _this.initWebSocket();
			},
			fail() {
				console.log('用户拒绝录音权限');
				uni.showModal({
					title: '提示',
					content: '录音需要授权，请前往设置打开权限',
					success(res) {
						if (res.confirm) {
							uni.openSetting(); // 打开设置页面引导用户授权
						}
					}
				});
			}
		});
	},
	// 页面卸载时关闭 WebSocket
	onUnload() {
		// this.closeWebSocket();
	}
};
</script>

<style>
.content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.logo {
	height: 200rpx;
	width: 200rpx;
	margin-top: 200rpx;
	margin-left: auto;
	margin-right: auto;
	margin-bottom: 50rpx;
}

.text-area {
	display: flex;
	justify-content: center;
}

.title {
	font-size: 36rpx;
	color: #8f8f94;
}
</style>
